# _*_ coding:utf-8 _*_
# @Time  : 2023.08.25
# @Author: zizlee
import json
import pathlib
import datetime
import itertools
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
from utils import datetime_utils
from settings import FILE_STORAGE, STATIC_HOST
# Agg, is a non-interactive backend that can only write to files.
matplotlib.use('agg')  # 避免警告： UserWarning: Starting a Matplotlib GUI outside of the main thread will likely fail.
plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文
plt.rcParams["axes.unicode_minus"] = False


class MixAppraise:
    TEMP_FOLDER = pathlib.Path(FILE_STORAGE).joinpath('sysTemp/exDoctor')

    def get_evaluation_score(self, rate_range, score_range, rate):
        if rate <= rate_range[0]:
            return score_range[0]
        if rate >= rate_range[1]:
            return score_range[1]
        score_upper = (score_range[1] - score_range[0]) * ((rate - rate_range[0]) / (rate_range[1] - rate_range[0]))
        return int(score_range[0] + score_upper)

    def get_appraise(self, score, reverse=False):
        if reverse:
            if score <= 20:
                appraise = '优秀'
            elif 20 < score <= 40:
                appraise = '良好'
            elif 40 < score <= 60:
                appraise = '一般'
            elif 60 < score <= 80:
                appraise = '不足'
            else:
                appraise = '严重不足'
        else:
            if score <= 20:
                appraise = '严重不足'
            elif 20 < score <= 40:
                appraise = '不足'
            elif 40 < score <= 60:
                appraise = '一般'
            elif 60 < score <= 80:
                appraise = '良好'
            else:
                appraise = '优秀'
        return appraise

    def get_valuation_appraise(self, account_overview, close_overview):
        account_overview_dict = {i['key']: i['value'] for i in account_overview}
        close_overview_dict = {j['key']: j['value'] for j in close_overview}
        # 盈利能力(年化收益率)
        annualized_profit_ratio = account_overview_dict.get('annualized_profit_ratio', 0)
        if annualized_profit_ratio < -0.25:
            rate, score = [-0.5, -0.26], [5, 20]
        elif -0.25 <= annualized_profit_ratio < 0:
            rate, score = [-0.25, 0.001], [20, 40]
        elif 0 <= annualized_profit_ratio < 0.3:
            rate, score = [0.001, 0.3], [40, 60]
        elif 0.3 <= annualized_profit_ratio < 0.6:
            rate, score = [0.3, 0.6], [60, 80]
        else:
            rate, score = [0.6, 1.2], [80, 100]
        yl_score = self.get_evaluation_score(rate, score, annualized_profit_ratio)
        yl_obj = {
            'name': '盈利能力',
            'value': annualized_profit_ratio,
            'score': yl_score,
            'appraise': self.get_appraise(yl_score),
            'key': 'yl'
        }

        # 风控能力评价：最大回撤率0.6与风险度均值各0.4
        max_withdraw_ratio_num = account_overview_dict.get('max_withdraw_ratio', 0)
        if max_withdraw_ratio_num < 0.08:
            sr, score = [0, 0.08], [80, 100]
        elif 0.08 <= max_withdraw_ratio_num < 0.16:
            sr, score = [0.09, 0.16], [60, 80]
        elif 0.16 <= max_withdraw_ratio_num < 0.24:
            sr, score = [0.16, 0.24], [40, 60]
        elif 0.24 <= max_withdraw_ratio_num < 0.32:
            sr, score = [0.24, 0.32], [20, 40]
        else:
            sr, score = [0.32, 0.4], [0, 20]
        max_withdraw_ratio_score = self.get_evaluation_score(sr, score, max_withdraw_ratio_num)
        average_risk_rate_num = account_overview_dict.get('average_risk_ratio', 0)

        if average_risk_rate_num < 0.3:
            sr, score = [0, 0.3], [80, 100]
        elif 0.3 <= average_risk_rate_num < 0.5:
            sr, score = [0.3, 0.5], [60, 80]
        elif 0.5 <= average_risk_rate_num < 0.7:
            sr, score = [0.5, 0.7], [40, 60]
        elif 0.7 <= max_withdraw_ratio_num < 1:
            sr, score = [0.7, 1], [20, 40]
        else:
            sr, score = [1, 1.3], [0, 20]
        average_risk_rate_score = self.get_evaluation_score(sr, score, average_risk_rate_num)

        total_score = int(max_withdraw_ratio_score * 0.6 + average_risk_rate_score * 0.4)
        fk_score = total_score
        fk_obj = {
            'name': '风控能力',
            'value': 0,  # 风控能力fk_rate的这个数值是无法衡量的,是2个合并的，这里设置为0
            'score': fk_score,
            'appraise': self.get_appraise(fk_score),
            'key': 'fk'
        }

        # 业绩稳定性： 夏普比率
        sharpe_ratio = round(account_overview_dict.get('sharpe_ratio', 0), 4)
        if sharpe_ratio < -0.4:
            rate, score = [sharpe_ratio, -0.4], [5, 20]
        elif -0.4 <= sharpe_ratio < 0.3:
            rate, score = [-0.4, 0.3], [20, 40]
        elif 0.3 <= sharpe_ratio < 1:
            rate, score = [0.3, 1], [40, 60]
        elif 1 <= sharpe_ratio < 1.7:
            rate, score = [1, 1.7], [60, 80]
        else:
            rate, score = [1.8, 2.4], [80, 100]
        yj_score = self.get_evaluation_score(rate, score, sharpe_ratio)
        yj_obj = {
            'name': '业绩稳定性',
            'value': sharpe_ratio,
            'score': yj_score,
            'appraise': self.get_appraise(yj_score),
            'key': 'yj'
        }

        # 交易胜率评分
        sl_rate = close_overview_dict.get('success_ratio', 0)
        if sl_rate < 0.2:
            rate, score = [sl_rate, 0.2], [5, 20]
        elif 0.2 <= sl_rate < 0.4:
            rate, score = [0.2, 0.4], [20, 40]
        elif 0.4 <= sl_rate < 0.6:
            rate, score = [0.4, 0.6], [40, 60]
        elif 0.6 <= sl_rate < 0.8:
            rate, score = [0.6, 0.8], [60, 80]
        else:
            rate, score = [0.8, 1], [80, 100]
        sl_score = self.get_evaluation_score(rate, score, sl_rate)
        sl_obj = {
            'name': '交易胜率',
            'value': sl_rate,
            'score': sl_score,
            'appraise': self.get_appraise(sl_score),
            'key': 'sl'
        }
        return [yl_obj, fk_obj, yj_obj, sl_obj]

    # 生成账户评分雷达图
    def evaluation_appraise_radar(self, filename_prefix, fig_size, evaluation_data):
        fig = plt.figure(figsize=fig_size)
        ax = fig.add_subplot(projection='polar')
        labels = [i['name'] for i in evaluation_data]
        scores = [i['score'] for i in evaluation_data]
        angle = np.linspace(0, 2 * np.pi, len(evaluation_data), endpoint=False)  # data里有几个数据，就把整圆360°分成几份
        angles = np.concatenate((angle, [angle[0]]))  # 增加第一个angle到所有angle里，以实现闭合
        scores = np.concatenate((scores, [scores[0]]))  # 增加第一个data到所有的data里，以实现闭合
        labels = np.concatenate((labels, [labels[0]]))
        ax.set_thetagrids(angles * 180 / np.pi, labels)  # 设置网格标签
        ax.plot(angles, scores, 'o-')
        ax.set_theta_zero_location('NW')  # 设置极坐标0°的位置
        ax.set_rlim(0, 100)  # 设置极径范围
        ax.fill(angles, scores, facecolor='r', alpha=0.5)  # 填充颜色
        ax.set_rlabel_position(255)  # 设置极径标签位置
        plt.title('账户综合评分')
        img_file = self.TEMP_FOLDER.joinpath(f'{filename_prefix}_evaluation_score_radar.png')
        plt.savefig(img_file)
        plt.close()
        # 写入文件，生成pdf使用
        json_file = self.TEMP_FOLDER.joinpath(f'{filename_prefix}_evaluation_score.json')
        with open(json_file, 'w', encoding='utf8') as f:
            json.dump(evaluation_data, f, indent=2, ensure_ascii=False)
        img_filename = str(img_file).replace('\\', '/').replace(FILE_STORAGE, '')
        return {
            'img_file': img_filename,
            'img_url': STATIC_HOST + img_filename,
            'evaluation': evaluation_data
        }


class SyntheticalAppraise(object):
    TEMP_FOLDER = pathlib.Path(FILE_STORAGE).joinpath('sysTemp/exDoctor')

    def __init__(self, fund_data_list, close_data_list):
        self.fund_df = pd.DataFrame(fund_data_list)
        self.close_df = pd.DataFrame(close_data_list)
        # 每日盈亏
        self.fund_df['day_profit'] = self.fund_df['profit']
        # 盈亏标记
        self.fund_df['flag'] = self.fund_df['day_profit'].apply(lambda p: 1 if p > 0 else -1)
        # 账户总盈亏
        self.total_profit = self.fund_df['day_profit'].sum().round(2)

    # 1、胜率分析
    def success_ratio(self):
        total_count = self.close_df.shape[0]
        gain_count = self.close_df[self.close_df['profit_close'] > 0].shape[0]
        loss_count = total_count - gain_count
        sr = gain_count / total_count
        # 查看统计期最后一个交易日的浮动盈亏
        # last_drift_profit = self.fund_df.iloc[-1]['profit_drift']
        # 总浮动盈亏
        total_drift_profit = self.fund_df['profit_drift'].sum()

        text1 = f'您的账户在整个交易期间共平仓交易{total_count}笔，其中获利{gain_count}笔，亏损{loss_count}笔。'
        if self.total_profit > 0:
            if sr > 0.6:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，恭喜您！胜率很高，远远高于市场的平均胜率（35%左右），希望您一直保持自己的交易风格，计划您的交易，交易您的计划。"
            elif 0.4 < sr <= 0.6:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，高于市场平均胜率（35%左右），您有较好的盘感，对市场的变化,也相对敏感，希望您保持稳定的心态，再接再厉，创造更高的成绩。"
            elif 0.3 < sr <= 0.4:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，接近市场平均胜率（35%左右）,推荐您阅读《期货市场技术分析》、《日本蜡烛图》等书籍，进一步加强技术分析的学习和研究，保持平稳的心态，并随时同瑞达期货各营业部客服人员沟'通，了解瑞达期货推出的一些咨询服务产品和程序化交易产品,帮助您提高胜率。"
            else:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，低于市场平均胜率（35%左右），建议您放松一下心情，顺便给自己充一下电吧。"
                if total_drift_profit > 0:
                    text1 += '不过您截止统计期期末仍有持仓，且浮动盈利，提升了整体账户盈亏情况。'
                text1 += '推荐您阅读《期货市场技术分析》、《日本蜡烛图》等书籍，努力加强技术分析的研究，并随时同瑞达期货各营业部客服人员沟通，了解瑞达期货推出的一些咨询服务产品程序化交易产品，帮助您提高胜率。'
        else:
            if sr > 0.6:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，胜率很高，远远高于市场的平均胜率（35%左右），这是一个极端的案例，您拥有极高的天赋，但盈亏比结果不理想，仓位管理可能也存在问题，盈利时的仓位较小，而亏损时的仓位较重，"
                if total_drift_profit < 0:
                    text1 += f'而您截止到统计期期末仍有持仓，且浮动亏损，降低了整体账户盈亏情况，导致整体账户亏损。'
                else:
                    text1 += '导致整体账户亏损。'
            elif 0.4 < sr <= 0.6:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，高于市场平均胜率（35%左右），但是您的账户总体净盈亏依然亏损，您有较高的盘感对市场的变化也相对敏感，但比较欠缺资金和仓位的管理，往往盈利的轻仓而亏损的满仓或重仓，导致整体账户亏损。"
            elif 0.3 < sr <= 0.4:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，接近市场平均胜率（35%左右）,但您的账户净盈亏依然亏损，推荐您阅读《期货市场技术分析》、《日本蜡烛图》等书籍，加强资金和仓位的管理，保持平稳的心态，并随时同瑞达期货各营业部客服人员沟通，了解瑞达期货推出的一些咨询服务产品和程序化交易产品，帮助您提高胜率。"
            else:
                text1 += f"您的胜率为{round(sr * 100, 2)}%，低于市场平均胜率（35%左右），建议您放松一下心情，顺便给自己充一下电吧。推荐您阅读《期货市场技术分析》、《日本蜡烛图》等书籍，努力加强技术分析的研究，并随时同瑞达期货各营业部客服人员沟通，了解瑞达期货推出的一些咨询服务产品程序化交易产品，帮助您提高胜率。"

        return text1

    # 2、单笔盈亏分析
    def signal_exchange_profit(self):
        highest_gain = self.close_df[self.close_df['profit_close'] > 0]['profit_close'].max()  # 单笔最高获利
        highest_gain = int(highest_gain)
        average_gain = self.close_df[self.close_df['profit_close'] > 0]['profit_close'].mean()  # 平均每笔获利
        average_gain = int(average_gain)
        highest_loss = self.close_df[self.close_df['profit_close'] <= 0]['profit_close'].min()  # 单笔最高亏损
        highest_loss = int(abs(highest_loss))
        average_loss = self.close_df[self.close_df['profit_close'] <= 0]['profit_close'].mean()  # 平均每笔亏损
        average_loss = int(abs(average_loss))

        if average_gain == 0:
            multi1 = 0
            highest_gain = 0
        else:
            multi1 = int(highest_gain / average_gain)  # 倍数1，最高获利/平均获利

        if average_loss == 0:
            multi2 = 0
            highest_loss = 0
        else:
            multi2 = int(highest_loss / average_loss)  # 倍数2，最高亏损/平均亏损

        text2 = f"您的账户单笔最高获利为{highest_gain}元，是平均每笔获利的{multi1}倍；单笔最高亏损为{highest_loss}元，是平均每笔亏损的{multi2}倍。"
        # 倍数判断
        if multi1 >= 20:
            text2 += "您的最高获利或最高亏损金额远远大于平均每笔获利金额，造成了您账户资金的不稳定性，最高获利较大有可能因抓住一波趋势单或重仓单有关。"
        elif 10 <= multi1 < 20:
            text2 += "您的单笔获利比例在正常范围之内，建议您进一步学习一些交易的理念和技巧，制定您擅长的交易计划，并做好风险控制。"
        else:
            if self.total_profit < 0:  # 亏损的账户
                total_loss = self.close_df[self.close_df['profit_close'] <= 0]['profit_close'].sum()  # 总亏损
                max_loss_rate = highest_loss / total_loss if total_loss != 0 else 1
                if abs(max_loss_rate) > 0.3:  # 单笔亏损占总亏损30%以上
                    text2 += "您曾单次交易造成大亏，应注意是抗跌不止损造成的或者是过于重仓导致的。"
                else:
                    text2 += "您单笔亏损并未出现过大的情况，交易过程中有注意仓位管理和风险控制。"
            else:
                total_gain = self.close_df[self.close_df['profit_close'] > 0]['profit_close'].sum()  # 总盈利
                max_gain_rate = highest_gain / total_gain if total_gain != 0 else 1
                if abs(max_gain_rate) > 0.3:  # 单笔盈利占总盈利的30%
                    text2 += "您交易中曾单笔获得较大收益，应注意自己这一单交易是较大仓位（或重仓）获取的还是获得较大的行情波动趋势而来。"
                elif multi1 == 0 and highest_gain == 0:  # 没有获利的情况
                    text2 += "您平仓的交易记录中没有获利的情况，建议您进一步学习一些交易的理念和技巧，制定您擅长的交易计划，并做好风险控制。"
                else:
                    text2 += "您交易中各笔获利较正常，无突出表现，要么是投入仓位太轻要么就是行情趋势幅度的捕捉基本比较小导致。"

        if multi2 >= 20:
            text2 += "最高亏损较大有可能因没有注意盘面变化、做错单未及时止损、单日重仓、或出现极端单边行情等有关，建议严格控制仓位，金字塔加码做单，同时设置好止损位。并严格执行您的交易计划。"
        elif 10 <= multi2 < 20:
            text2 += "您的单笔亏损比例在正常范围之内，建议您进一步学习一些交易的理念和技巧，制定您擅长的交易计划，并做好风险控制。"
        elif multi2 == 0 and highest_loss == 0:  # 没有亏损的情况
            text2 += '您平仓交易记录中没有亏损的情况，您拥有非常好的交易理念和技巧。'
        else:
            text2 += "您单笔最大亏损控制得较好，未出现单笔过大风险。"
        return text2

    # 3、平均盈亏比分析
    def gain_loss_percent(self):
        average_gain = self.close_df[self.close_df['profit_close'] > 0]['profit_close'].mean()  # 平均每笔获利
        average_loss = self.close_df[self.close_df['profit_close'] <= 0]['profit_close'].mean()  # 平均每笔亏损
        average_gain = int(average_gain)
        average_loss = int(abs(average_loss))
        if average_loss == 0:
            multi = 0
        else:
            multi = round(average_gain / average_loss, 2)
        text3 = f"您的账户平均每笔获利{average_gain}，平均每笔亏损{average_loss}，平均盈亏比(平均每笔获利/平均每笔亏损)为{multi}。"
        if multi > 3:
            text3 += "您的平均盈亏很高，只要平常的胜率下就能盈利。"
        elif 1.5 < multi <= 3:
            text3 += "您的平均盈亏比较高，只要总体胜率不过低，即能取得综合盈利。"
        elif 1 < multi <= 1.5:
            text3 += "您的平均盈亏比比较普通，后期建议进一步提升盈亏比的空间。"
        elif 0.6 < multi <= 1:
            text3 += "您的平均盈亏比较低，后期可以适当改进盈亏方面的比例，当然如果您的胜率非常高的情况也是能最终获利的。"
        elif 0.3 < multi <= 0.6:
            text3 += "您的平均盈亏比过低，这种情况想要获利只能是非常高的胜率才行，建议后期改进盈亏比的空间。"
        elif multi == 0 and average_loss == 0:
            text3 += "(您的平仓记录中没有亏损的情况，盈亏比数据失效。)"
        else:
            text3 += "您的平均盈亏比太低，除非您有极高的胜率才可能最终获利。盈亏比方面您需要有较大的提升。"
        return text3

    # 4、连续盈亏天数分析
    def profit_conn_days(self):
        daily_df = self.fund_df.sort_values(by='ex_date')
        gain_con_day_count = max(sum(g) for k, g in itertools.groupby(daily_df['flag']) if k == 1)
        loss_con_day_count = max(-sum(g) for k, g in itertools.groupby(daily_df['flag']) if k == -1)
        text4 = f"您的账户连续获利的最高天数是{gain_con_day_count}天，连续亏损最高的天数是{loss_con_day_count}天，"
        if gain_con_day_count >= loss_con_day_count:
            if gain_con_day_count >= 15:
                text4 += "您交易对行情判断能力非常强且具有一定的持续性和稳定性。"
            elif 5 <= gain_con_day_count < 15:
                text4 += "您交易对行情判断能力比较强且具有一定的持续性。"
            else:
                text4 += "您交易中未有持续判断准确并交易的情况，还有待提升分析交易能力。"
        else:
            if loss_con_day_count >= 15:
                text4 += "您交易中出现恶性持续的亏损，可能您的分析能力较差进场判断错误行情，且交易中心态可能非常不好导致，后期应特别注意。"
            elif 5 <= loss_con_day_count < 15:
                text4 += "您交易中曾出现一定时间的持续亏损，这与您的分析能力和交易心态相关，后期应注意。"
            else:
                text4 += "你连续亏损的交易日时间并不长，属于正常现象。"
        return text4

    # 5、持仓时间分析
    def holding_days(self):
        temp_df = self.close_df.copy()
        temp_df['ex_date_o'] = temp_df['ex_date'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d'))
        temp_df['date_open_o'] = temp_df['date_open'].apply(lambda x: datetime.datetime.strptime(str(x), '%Y%m%d'))
        temp_df['day_count'] = temp_df.apply(lambda x: len(datetime_utils.get_exchange_days(x['date_open_o'], x['ex_date_o'])), axis=1)
        # del temp_df['day_interval']
        gain_avg_days = temp_df[temp_df['profit_close'] > 0]['day_count'].mean()  # 盈利单平均持仓天数
        gain_avg_days = round(gain_avg_days, 2)
        loss_avg_days = temp_df[temp_df['profit_close'] <= 0]['day_count'].mean()  # 亏损单平均持仓天数
        loss_avg_days = round(loss_avg_days, 2)
        text5 = f"您的账户获利单的平均持仓时间是{gain_avg_days}个交易日，亏损单的平均持仓时间是{loss_avg_days}个交易日。"
        if self.total_profit > 0:
            if gain_avg_days > loss_avg_days:
                if gain_avg_days > 1:
                    text5 += "您有很好的交易理念，也有很好的耐心，账户盈利时能够坚定持仓，亏损时则能及时出场。"
                else:
                    text5 += "您作风雷厉风行，偏好短期持仓，是日内交易的好手。"
            else:
                if gain_avg_days > 1:
                    text5 += "您总是独具慧眼，能在一波行情即将快速启动的时候抓住尾巴。"
                else:
                    text5 += "您谨慎入微，有利润就偏好立即放进自己的口袋，亏损时有一种不服输的死扛劲头。"
        else:
            if gain_avg_days > loss_avg_days:
                if gain_avg_days > 1:
                    text5 += "您花了很长的时间来等待果实的收货，却迷失在较多的干扰中，反而导致账户整体亏损。"
                else:
                    text5 += "您是日内短期交易的忠实粉丝，然而行情在日内难免反复，把握不好多空原则很容易导致账户整体亏损。"
            else:
                if gain_avg_days > 1:
                    text5 += "您希望在获取利润的同时规避风险，但是却害怕风险，因此总是在获利时匆忙出场，亏损时犹豫守仓。"
                else:
                    text5 += "您是日内短期交易的忠实粉丝，然而行情在日内难免反复，把握不好多空原则很容易导致账户整体亏损。"
        return text5

    # 6、交易操作分析
    def exchange_operation(self):
        text6 = ""
        temp_df = self.close_df.groupby(by='variety_name', as_index=False)['profit_close'].sum()
        gain_df = temp_df[temp_df['profit_close'] > 0]
        suggest_access_variety = ''
        suggest_avoid_variety = ''
        if gain_df.empty:
            text6 += '您没有获利的品种。'
        else:
            gain_df = gain_df.sort_values(by='profit_close', ascending=False)
            total_gain = gain_df['profit_close'].sum()
            max_gain_variety = gain_df.head(1).to_dict(orient='records')[0]
            # 解读获利的情况
            gain_variety_list = gain_df['variety_name'].tolist()
            if total_gain == 0:
                max_gain_rate = 1
            else:
                max_gain_rate = round(max_gain_variety['profit_close'] / total_gain, 4)
            suggest_access_variety = max_gain_variety['variety_name']
            text6 += f"您平仓获利较大的品种有：{'、'.join(gain_variety_list[:8])}，"
            text6 += f"盈利最大的品种为：{suggest_access_variety}，净盈利为：{max_gain_variety['profit_close']}，净盈利比例达{round(max_gain_rate * 100, 2)}%；"

        loss_df = temp_df[temp_df['profit_close'] <= 0].copy()
        if loss_df.empty:
            text6 += '您没有亏损的品种。'
        else:
            loss_df['profit_close'] = loss_df['profit_close'].apply(abs)
            loss_df.sort_values(by='profit_close', ascending=False, inplace=True)
            total_loss = loss_df['profit_close'].sum()
            max_loss_variety = loss_df.head(1).to_dict(orient='records')[0]
            # 解读亏损的情况
            loss_variety_list = loss_df['variety_name'].tolist()
            if total_loss == 0:
                max_loss_rate = 1
            else:
                max_loss_rate = round(max_loss_variety['profit_close'] / total_loss, 4)
            suggest_avoid_variety = max_loss_variety['variety_name']
            text6 += f"您平仓亏损较大的品种有：{'、'.join(loss_variety_list[:8])}，"
            text6 += f"亏损最大的品种为：{suggest_avoid_variety}，净亏损为：{max_loss_variety['profit_close']}，净亏损比例达{round(max_loss_rate * 100, 2)}%；"
        if suggest_access_variety:
            text6 += f"我们建议您尽量操作自己熟悉并且获利较大的品种，在提高自己成就感的同时实实在在的获得利润。"
        if suggest_avoid_variety:
            text6 += f"当然同巴菲特绝不买入陌生公司的股票一样，我们同时建议您回避自己陌生并且亏损较大的品种。"
        return text6

    def synthesize(self, filename_prefix):
        synthesize_data = [
            {'name': '胜率分析', 'key': 'success_ratio', 'text': self.success_ratio()},
            {'name': '单笔盈亏分析', 'key': 'signal_exchange_profit', 'text': self.signal_exchange_profit()},
            {'name': '平均盈亏比分析', 'key': 'gain_loss_percent', 'text': self.gain_loss_percent()},
            {'name': '连续盈亏天数分析', 'key': 'profit_conn_days', 'text': self.profit_conn_days()},
            {'name': '持仓时间分析', 'key': 'holding_days', 'text': self.holding_days()},
            {'name': '交易操作分析', 'key': 'exchange_operation', 'text': self.exchange_operation()},
        ]

        with open(self.TEMP_FOLDER.joinpath(f'{filename_prefix}_synthetical_appraise.json'), 'w', encoding='utf8') as f:
            json.dump(synthesize_data, f, indent=2, ensure_ascii=False)
        return synthesize_data

